package cn.chenyumeng.blog.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密类
 *
 * @program: blog->MD5Utils
 * @description: MD5加密类
 * @author: cg
 * @create: 2020-07-27 11:06
 **/
public class MD5Utils {

    /**
     * MD5加密
     * @param source
     * @return
     */
    public static String code(String source) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source.getBytes());
            byte[] digest = md.digest();
            int i;
            StringBuffer stringBuffer = new StringBuffer("");
            for (int offset = 0; offset < digest.length; offset++) {
                i = digest[offset];
                if(i<0) {
                    i+=256;
                }
                if (i<16) {
                    stringBuffer.append("0");
                }
                stringBuffer.append(Integer.toHexString(i));
            }
            // 32位加密
            return stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}
